<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form :form="form" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
                    <a-form-item style="display: none;">
                        <a-input v-decorator="['settingType']" />
                        <a-input v-decorator="['boListId']" />
                        <a-input v-decorator="['boListKey']" />
                        <a-input v-decorator="['menuType']" />
                        <a-input v-decorator="['component']" />
                        <a-input v-decorator="['params']"
                            v-if="settingType == 'custom' || settingType == 'form' || settingType == 'list' || settingType == 'bpm'" />
                    </a-form-item>
                    <a-form-item :labelCol1="labelCol1" :wrapperCol1="wrapperCol1" :label="$ti18('rxForm.appId', '应用')">
                        <a-select v-if="!curAppObj || !curAppObj.appId"
                            v-decorator="['appId', { initialValue: '', rules: [{ required: true, message: i18n('msa.selectApp', '请选择应用') }] }]"
                            @select="handleAppChange">
                            <a-select-option v-for="(action) in sysAppAllData" :key="action.appId">
                                {{ $i18(action.clientName, '应用名称') }}
                            </a-select-option>
                        </a-select>
                        <div v-else>
                            {{ curAppObj.appName }}
                        </div>

                    </a-form-item>


                    <a-form-item :labelCol1="labelCol1" :wrapperCol1="wrapperCol1"
                        :label="$comi18('business.parentMenu', '父菜单')">
                        <a-tree-select v-decorator="['parentId']"
                            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }" :treeData="treeData"
                            :placeholder="$comi18('business.parentMenu', '请选择父菜单', 'select')" allowClear>
                        </a-tree-select>
                    </a-form-item>


                    <a-form-item :labelCol1="labelCol1" :wrapperCol1="wrapperCol1" :label="$ti18('rxForm.name', '名称')">
                        <rx-input-i18n :placeholder="$ti18('rxForm.name', '请输入名称', '', 'input')" :isDecorator="true"
                            v-decorator="['name', { rules: [{ required: true, message: $ti18('rxForm.name', '请输入名称', '', 'input') }] }]" />
                    </a-form-item>

                    <a-form-item :labelCol1="labelCol1" :wrapperCol1="wrapperCol1"
                        :label="$comi18('business.aliasKey', '标识键')">
                        <a-input
                            v-decorator="['menuKey', { initialValue: '', rules: [{ required: true, message: i18n('msa.menuKeyDesc', '请输入动态菜单唯一键') }] }]"
                            :placeholder="$comi18('business.aliasKey', '标识键：如user', 'input')" />
                    </a-form-item>

                    <a-form-item v-if="settingType == 'iframe'" :labelCol1="labelCol1" :wrapperCol1="wrapperCol1"
                        label="URL">
                        <a-input v-decorator="['params']" :placeholder="$ti18('rxDecorator.input', '请输入') + 'URL'" />
                    </a-form-item>

                    <a-form-item :labelCol1="labelCol1" :wrapperCol1="wrapperCol1"
                        :label="$comi18('business.icon', '图标')">
                        <rx-select-icon
                            v-decorator="['iconPc', { rules: [{ required: true, message: $comi18('business.icon', '图标', 'select') }] }]"
                            :base-url="baseUrl"></rx-select-icon>
                    </a-form-item>
                    <a-form-item :labelCol1="labelCol1" :wrapperCol1="wrapperCol1"
                        :label="$comi18('business.accessMode', '访问方式')">
                        <a-radio-group :options="showTypeOptions"
                            v-decorator="['showType', { initialValue: 'URL', rules: [{ required: true, message: $comi18('business.accessMode', '请选择访问方式', 'select') }] }]" />
                    </a-form-item>
                    <a-form-item :labelCol1="labelCol1" :wrapperCol1="wrapperCol1"
                        :label="$comi18('business.displayOrder', '显示顺序')">
                        <a-input-number
                            v-decorator="['sn', { initialValue: 1, rules: [{ required: true, message: $comi18('business.displayOrder', '请输入顺序数字', 'input') }] }]"
                            :placeholder="$comi18('business.displayOrder', '显示顺序')" />
                    </a-form-item>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import SysMenuApi from '@/api/system/core/sysMenu'
import SysAppApi from '@/api/system/core/sysApp'

import { BaseForm, RxDialog, Util, RxInputI18n, RxSelectIcon } from "@lowcode/jpaas-common-lib";

export default {
    name: 'SysMenuAddNode',
    mixins: [BaseForm],
    props: {
        //关联的菜单ID
        releaseId: String,
        //菜单名称
        name: String,
        //菜单KEY
        mKey: String,
        //菜单组件
        component: String,
        //菜单参数 (如果是组件，那么这个是存放组件的参数，如果是IFRAME 这个是放 URL)
        params: Object,
        boListId: String,
        // 这个比较特殊 只有列表的时候才使用。
        boListKey: String,
        //当前应用对象
        curAppObj: Object,
        settingType: {
            type: String,
            default: "custom"
        }
    },
    components: {
        RxDialog,
        RxInputI18n, RxSelectIcon
    },
    data() {
        return {
            showTypeOptions: [
                { label: this.$comi18('business.urlRequest', 'URL访问'), value: 'URL' },
                { label: this.$comi18('business.openWind', '弹窗'), value: 'POP_WIN' },
                { label: this.$comi18('business.nweWind', '新窗口'), value: 'NEW_WIN' }
            ],
            sysAppAllData: [],
            treeData: [],
            menuType: "C",
            iconPc: '',
            joinBtns: false,
            baseUrl: process.env.VUE_APP_ADMIN_FRONT
        }
    },
    created() {
        //加载应用菜单。
        if (this.curAppObj && this.curAppObj.appId) {
            this.getMenusByAppId(this.curAppObj.appId);
        }
        else {
            this.loadAllSysApp();
        }

    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "sysMenu", key);
        },
        changeJoinBtns(value) {
            this.joinBtns = !value;
        },
        onload_() {
            var isStr = typeof this.params == "object";
            var params = this.params;
            if (isStr) {
                params = JSON.stringify(params)
            }
            this.mdl = Object.assign({
                name: this.name,
                boListId: this.boListId,
                boListKey: this.boListKey,
                menuKey: this.mKey,
                menuType: "C",
                component: this.component,
                params: params,
                settingType: this.settingType
            });
            // 如果标识键为空才计算
            if (!this.mdl.menuKey) {
                let self = this;
                this.getPinyin(this.mdl.name).then(res => {
                    //去除不可见的特殊符号
                    if (res) {
                        res = res.replace(/\u200B/g, '');
                    }
                    self.mdl.menuKey = res
                })
            }
            this.form.setFieldsValue(this.mdl)
        },
        get(id) {
            return SysMenuApi.get(id);
        },
        save(values) {
            values.releaseId = this.releaseId;
            values.joinBtns = this.joinBtns;
            if (this.curAppObj && this.curAppObj.appId) {
                values.appId = this.curAppObj.appId;
            }
            return SysMenuApi.saveSysMenu(values);
        },
        loadAllSysApp() {
            SysAppApi.getById(this.curAppObj ? this.curAppObj.appId : this.curApp.appId).then(res => {
                this.sysAppAllData = res.data;
            })
        },
        handleAppChange(value) {
            this.getMenusByAppId(value);
        },
        /**
         * 根据应用ID获取菜单。
         * @param appId
         */
        getMenusByAppId(appId) {
            this.treeData.length = 0;
            SysMenuApi.getAllSysMenuListByAppId({ appId: appId }).then(res => {
                this.buildtree(res, this.treeData, '0')
            })
        },
        buildtree(list, arr, parentId) {
            list.forEach(item => {
                if (item.parentId === parentId) {
                    var child = {
                        key: item.id,
                        value: item.id + '',
                        title: this.$i18(item.name, '父菜单名称'),
                        children: []
                    }
                    this.buildtree(list, child.children, item.id)
                    arr.push(child)
                }
            })
        },
        handleSubmit(vm) {
            this.form.validateFields((err, values) => {
                if (!Util.hasChineseAndSpecialChars(values.menuKey)) {
                    this.$message.warning('标识中不能包含中文以及特殊字符~');
                    vm.loading = false;
                    return;
                }
                if (err) {
                    vm.loading = false;
                    return;
                }
                let routeId = this.$route.params.id;
                if (this.pkId) {
                    values.pkId = this.pkId;
                } else {
                    if (routeId && routeId != "add") {
                        values.pkId = routeId;
                    } else {
                        values.pkId = ''
                    }
                }
                this.confirmLoading = true;
                if (this.validForm) {
                    var flag = this.validForm(values);
                    if (!flag) {
                        vm.loading = false;
                        return;
                    }
                }
                let appId = this.curAppObj ? this.curAppObj.appId : this.curApp.appId;
                if (appId && !this.pkId) {
                    values.appId = appId;
                }
                this.onSubmit(values);
                let _self = this;
                this.save(values, vm).then(res => {
                    if (res.success && res.code == 200) {
                        //返回结果数据。
                        this.resultData = res.data;
                        let _layerid = this.layerid;//根据判断有没有弹窗的id来判断是不是弹窗方式打开的页面 ;
                        if (_self.showType != "newPage") {
                            if (_layerid) {
                                Util.closeWindow(this, "ok", res.data);
                            } else {
                                this.$bus.emit("closeTab", { action: "current" });
                            }
                        }
                        vm.loading = false;
                    }
                }).catch(() => {
                    this.$message.error(this.$ti18('rxMsa.sysError', '系统错误，请稍后再试!'))
                    vm.loading = false;
                }).finally(() => {
                    this.confirmLoading = false;
                    vm.loading = false;
                })
            })
        }
    }
}


</script>
